package com.hsq.namall.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取请求参数
        //3.获取请求cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        System.out.println("token====>"+cookies.get("token"));
        //4.获取请求的头---任何请求都必须在请求携带token
        HttpHeaders headers = request.getHeaders();
        List<String> token = headers.get("Cookie");
        if(token==null||token.size()==0){
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(HttpStatus.BAD_REQUEST.value());
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            DataBuffer buffer = response.bufferFactory().wrap("{\"id\":500,\"msg\":\"请先登录\"}".getBytes(StandardCharsets.UTF_8));
            return  response.writeWith(Flux.just(buffer));
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;//值越小 过滤器越先执行
    }
}
